package com.example.smartmedicalsystem.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        String redirectUrl = "/login.html?error"; // 默认错误页
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            // static目录下的患者页面
            redirectUrl = switch (authority.getAuthority()) {
                case "ROLE_ADMIN" -> "/admin.html"; // static目录下的管理员页面
                case "ROLE_DOCTOR" -> "/doctor.html"; // static目录下的医生页面
                case "ROLE_PATIENT" -> "/patient.html";
                default -> redirectUrl;
            };
            if (!redirectUrl.equals("/login.html?error")) break;
        }
        response.sendRedirect(redirectUrl);
    }
}